import { readFileSync } from 'fs'
import { ensureFile } from './ensure-path'
import eol from 'eol'
import { readJsonSync } from 'fs-extra'
import { resolve } from 'path'

export function getJSON<T>(
  path: string,
  defaultValues: Partial<T>,
): Partial<T> {
  ensureFile(path, eol.auto(JSON.stringify(defaultValues, null, 2)))
  try {
    return { ...defaultValues, ...JSON.parse(readFileSync(path).toString()) }
  } catch {
    return defaultValues
  }
}



export const jsonGet = (json: any, keys: string[]) => {
  let value = json
  for (let k of keys) {
    if (value) {
      value = value[k]
    } else {
      console.log('not found ', keys)
      return undefined
    }
  }
  return value
}

export const getJsonAt = (() => {
  const jsonCache: { [x: string]: any } = {}
  return (pathAt: string) => {
    const path = pathAt.split('/')
    const fileName = path[0]
    if (!jsonCache[fileName]) {
      jsonCache[fileName] = readJsonSync(resolve(`${fileName}.json`))
    }
    return jsonGet(jsonCache[fileName], path[1].split('.'))
  }
})()